import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import moment from 'moment';

import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Button,
  Menu,
  DatePicker, Divider, message, Modal, Dropdown, Icon, Tooltip,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import { financeMode, repayMode, status } from '../../../common/options';
import { powerBtnFunc } from '@/utils/utils';

import styles from '../UserManage.less';
import UpdateForm from './createFrom';
import DrawerComponent from './drawerInfo';
import CheckCompany from '../Company/check';

const Option = Select.Option;
const FormItem = Form.Item;

/* eslint react/no-multi-comp:0 */
@connect(({ equityModels, loading }) => ({
  equityModels,
  loading: loading.models.equityModels,
}))

@Form.create()
class UserManage extends PureComponent {
  constructor(props) {
    super(props);
  }

  state = {
    visibleCheck: false,
    modalVisible: false,
    visibleDrawer: false,
    lookDescView: false,
    selectedRows: {},
    formValues: {},
    pagination: {
      pageNo: 1,
      pageSize: 15,
    },
  };
  columns = [
    {
      title: '申请编码',
      dataIndex: 'applyNo',
      key: 'applyNo',
    },
    {
      title: '企业名称',
      key: 'enterpriseName',
      dataIndex: 'enterpriseName',
    },
    {
      title: '申请人',
      dataIndex: 'createName',
      key: 'createName',
    },
    {
      title: '融资天数',
      key: 'totalDays',
      dataIndex: 'totalDays',
    },
    {
      title: '融资金额',
      key: 'amount',
      dataIndex: 'amount',
    },
    {
      title: '融资方式',
      key: 'financeType',
      dataIndex: 'financeType',
      render: val => <span>{financeMode.map(item => (
        item.key === val ? item.value : ''
      ))}</span>,
    },
    {
      title: '还款方式',
      key: 'repayMode',
      dataIndex: 'repayMode',
      render: val => <span>{repayMode.map(item => (
        item.key === val ? item.value : ''
      ))}</span>,
    },
    {
      title: '创建时间',
      key: 'createTime',
      dataIndex: 'createTime',
    },

    {
      title: '状态',
      key: 'status',
      render: val => <span>{status.map((item,index) => {
        return item.key === val.status ? (item.value === '驳回' ? <Tooltip key={index.toString()} title={val.reason}>
          驳回<Icon type="info-circle-o" style={{ marginRight: 4 }}/>
        </Tooltip> : item.value) : '';
      })}</span>,
    },
    {
      title: '操作',
      key: 'dataIndex',
      render: (text, record) => {
        const menu = (
          <Menu>
            {record.status !== 6 && record.status !== 3 && record.status !== 4 ?
              powerBtnFunc('100056',
                <Menu.Item key={'audit'}>
                  <a onClick={() => this.handleAudit(true, record)}>审核</a>
                </Menu.Item>,
              ) : ''
            }
            {record.status !== 3 ? '' :
              powerBtnFunc('100056',
                <Menu.Item key={'generator'}>
                  <a onClick={() => this.generator(record)}>生成产品</a>
                </Menu.Item>,
              )
            }
            {
              powerBtnFunc('100053',
                <Menu.Item key={'del'}>
                  <a onClick={() => this.handleMenuClick(record)}>删除</a>
                </Menu.Item>,
              )
            }

          </Menu>
        );
        return (<Fragment>
            {powerBtnFunc('100052',
              <a key={'edit'} disabled={record.status === 6 || record.status === 3}
                 onClick={() => this.handleModalVisible(true, record)}>修改</a>,
            )}
            {powerBtnFunc('100049',
              [<Divider key={'divider'} type="vertical"/>,
                <a key={'view'} onClick={() => this.visibleDrawerInfo(true, record)}>查看</a>],
            )}
            <Divider key={'Divider1'} type="vertical"/>
            <Dropdown overlay={menu}>
              <a className="ant-dropdown-link" href="#">
                更多 <Icon type="down"/>
              </a>
            </Dropdown>
          </Fragment>
        );
      },

    },
  ];


  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'equityModels/fetch',
      payload: {},
    });
  }

  handleLookDesc(record) {
    router.push({
      pathname: '/preloan/apply/applyInfos',
      query: {
        applyNo: record.applyNo,
      },
    });
  }


  // 审核
  handleAudit = (flag, record) => {
    this.setState({
      visibleCheck: !!flag,
      selectedRows: record,
    });
  };
  //审核
  passCheck = (flag, record) => {
    const { dispatch } = this.props;
    const { selectedRows, pagination } = this.state;
    let _this = this;
    dispatch({
      type: 'equityModels/audit',
      payload: { code: selectedRows.applyNo, ...record },
      callback(res) {
        if (res.code === 200) {
          _this.handleAudit(false, []);
          dispatch({
            type: 'equityModels/fetch',
            payload: {
              status: _this.state.status,
              ...pagination,
            },
          });
          message.success('操作成功');
        } else {
          message.error(res.errMsg);
        }

      },
    });
  };

  //生成产品
  generator(selectedRows) {
    const { dispatch } = this.props;
    const { pagination } = this.state;
    let _this = this;
    Modal.confirm({
      title: '确认',
      content: '确定是否生产品吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'equityModels/generator',
          payload: { applyNo: selectedRows.applyNo },
          callback(res) {
            if (res.code === 200) {
              _this.handleAudit(false, []);
              dispatch({
                type: 'equityModels/fetch',
                payload: {
                  status: _this.state.status,
                  ...pagination,
                },
              });
              message.success('生成成功');
            } else {
              message.success(res.errMsg);
            }

          },
        });
      },
    });
  }


  // 搜索
  handleSearch = (e) => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      fieldsValue.endTime = fieldsValue.endTime ? moment(fieldsValue.endTime).format('YYYY-MM-DD') : '';
      fieldsValue.startTime = fieldsValue.startTime ? moment(fieldsValue.startTime).format('YYYY-MM-DD') : '';
      dispatch({
        type: 'equityModels/fetch',
        payload: fieldsValue,
      });
    });
  };
  // 重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'equityModels/fetch',
      payload: {},
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;

    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="企业名称">
              {getFieldDecorator('enterpriseName')(<Input placeholder="请输入企业名称"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="企业简称">
              {getFieldDecorator('shortName')(<Input placeholder="请输入企业简称"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="融资方式">
              {getFieldDecorator('financeMode')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  {financeMode.map((item, index) => (
                    <Option value={item.key} key={item.key} disabled={item.disabled}>{item.value}</Option>
                  ))}
                </Select>,
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="还款方式">
              {getFieldDecorator('repayMode')(
                <Select placeholder="请选择还款方式" style={{ width: '100%' }}>
                  {repayMode.map(item => (
                    <Option value={item.key} key={item.key} disabled={item.disabled}>{item.value}</Option>
                  ))}
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="开始时间">
              {getFieldDecorator('startTime')(<DatePicker placeholder='请选择开始时间' style={{ width: '100%' }}/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="结束时间">
              {getFieldDecorator('endTime')(<DatePicker placeholder='请选择结束时间' style={{ width: '100%' }}/>)}
            </FormItem>
          </Col>


        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>

          <Col md={8} sm={24}>
        <span className={styles.submitButtons}>
        <Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>

        </span>
          </Col>
        </Row>
      </Form>
    );
  }

  handleStandardTableChange = (pagination) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    this.setState({
      pagination: {
        pageNo: pagination.current,
        pageSize: 15,
      },
    });
    const params = {
      pageNo: pagination.current,
      pageSize: 15,
      ...formValues,
    };

    dispatch({
      type: 'equityModels/fetch',
      payload: params,
    });
  };
  visibleDrawerInfo = (flag, data) => {
    const { dispatch } = this.props;
    let _this = this;
    if (flag) {
      dispatch({
        type: 'equityModels/getApplyDesc',
        payload: { code: data.applyNo },
        callback() {
          _this.setState({
            visibleDrawer: true,
          });
        },
      });
    } else {
      this.setState({
        visibleDrawer: false,
      });
    }
  };
  //新建显示窗口
  handleModalVisible = (flag, rows) => {
    this.setState({
      modalVisible: !!flag,
      selectedRows: rows || {},
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };
  handleMenuClick = (row) => {
    const { dispatch } = this.props;
    const { pagination } = this.state;
    Modal.confirm({
      title: '确认',
      content: '确定删除该融资申请吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'equityModels/remove',
          payload: {
            code: row.applyNo,
          },
          callback: (res) => {
            if (res.code === 200) {
              message.success('删除成功');
              this.setState({
                selectedRows: [],
              });
              dispatch({
                type: 'equityModels/fetch',
                payload: pagination,
              });
            } else {
              message.error(res.errMsg);
            }
          },
        });
      },
    });
  };


  render() {
    const { selectedRows, modalVisible, visibleCheck, visibleDrawer } = this.state;
    const { equityModels: { data, applyDesc = {} }, loading } = this.props;

    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      handleFormReset: this.handleFormReset,
    };
    return (
      <PageHeaderWrapper title="融资管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <div className={styles.tableListOperator}>
              {
                powerBtnFunc('100051',
                  <Button key={'create'} icon="plus" type="primary"
                          onClick={() => this.handleModalVisible(true, {})}>
                    申请融资
                  </Button>)
              }
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data ? data : []}
              rowKey='applyNo'
              rowSelectHide={true}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        {modalVisible ?
          <UpdateForm
            {...parentMethods}
            modalVisible={modalVisible}
            selectedRows={selectedRows}
          />
          : ''}
        <CheckCompany
          visibleCheck={visibleCheck}
          passCheck={this.passCheck}
          handleCheck={this.handleAudit}/>
        <DrawerComponent visible={visibleDrawer} applyDesc={applyDesc} onClose={this.visibleDrawerInfo}/>
      </PageHeaderWrapper>

    );
  }
}

export default UserManage;
